package com.lagou.work02.factory;

import com.lagou.work02.stereotype.MyAutowired;
import com.lagou.work02.stereotype.MyService;
import com.lagou.work02.stereotype.MyTransactional;
import com.lagou.work02.util.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@MyService
public class ProxyFactory {

    private TransactionManager transactionManager;

    @MyAutowired
    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getJDKProxy(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                Class<?> aClass = object.getClass();
                if (aClass.isAnnotationPresent(MyTransactional.class)) { // 类是否存在注解
                    transactionManager.beginTransaction();
                    try {
                        result = method.invoke(object,args);
                        transactionManager.commit();
                    }catch (Exception e) {
                        e.printStackTrace();
                        transactionManager.rollback();
                    }
                } else {
                    result = method.invoke(object,args);
                }
                return result;
            }
        });
    }

    public Object getCglibProxy(Object object){


        return Enhancer.create(object.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                Class<?> aClass = object.getClass();
                if (aClass.isAnnotationPresent(MyTransactional.class)) { // 类是否存在注解
                    transactionManager.beginTransaction();
                    try {
                        result = method.invoke(object,objects);
                        transactionManager.commit();
                    }catch (Exception e) {
                        e.printStackTrace();
                        transactionManager.rollback();
                    }
                } else {
                    result = method.invoke(object,objects);
                }
                return result;
            }
        });
    }

}
